package com.ruoyi.system.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.entity.*;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.system.service.ICustomerInfoService;

/**
 * 客户数据Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-09
 */
@Service
public class CustomerInfoServiceImpl implements ICustomerInfoService
{
    @Autowired
    private CustomerInfoMapper customerInfoMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private AiDeepseekAnswerTotalMapper aiDeepseekAnswerTotalMapper;

    @Autowired
    private AiRecordingDuanMapper aiRecordingDuanMapper;
    @Autowired
    private AiDeepseekAnswerMapper aiDeepseekAnswerMapper;
    @Autowired
    private AiRecordingChildMapper aiRecordingChildMapper;
    /**
     * 查询客户数据
     *
     * @param id 客户数据主键
     * @return 客户数据
     */
    @Override
    public CustomerInfo selectCustomerInfoById(Long id)
    {
        return customerInfoMapper.selectCustomerInfoById(id);
    }

    /**
     * 查询客户数据列表
     *
     * @param customerInfo 客户数据
     * @return 客户数据
     */
    @Override
    public List<CustomerInfo> selectCustomerInfoList(CustomerInfo customerInfo)
    {
        return customerInfoMapper.selectCustomerInfoList(customerInfo);
    }

    @Override
    public List<CustomerInfo> selectCustomerInfoListPermission(CustomerInfo customerInfo)
    {
       Long userId= SecurityUtils.getUserId();
        SysUserRole sysUserRole =new SysUserRole();
        sysUserRole.setRoleId(100L);
        sysUserRole.setUserId(userId);
        Integer coun= sysUserRoleMapper.countUserRoleByRoleIdUserId(sysUserRole);
        if (coun == 0 && userId!=1L){
            customerInfo.setUserId(userId);
        }
        customerInfo.setEffective("1");
        PageUtils.startPage();
        List<CustomerInfo> customerInfoList=  customerInfoMapper.selectCustomerInfoListNoNull(customerInfo);
        customerInfoList.forEach(customerInfo1 -> {
            AiDeepseekAnswerTotal aiDeepseekAnswerTotal=new AiDeepseekAnswerTotal();
            aiDeepseekAnswerTotal.setCustomerId(customerInfo1.getId());
            List<AiDeepseekAnswerTotal>  aiDeepseekAnswerTotalList=  aiDeepseekAnswerTotalMapper.selectAiDeepseekAnswerTotalList(aiDeepseekAnswerTotal);
            customerInfo1.setAiDeepseekAnswerTotalList(aiDeepseekAnswerTotalList);
          Date time=  aiRecordingDuanMapper.selectFirstTime(customerInfo1.getId());
            customerInfo1.setFirstTime(null);
          if (time!=null){
              customerInfo1.setFirstTime(time);
          }




        });
        return customerInfoList;
    }

    public CustomerInfo selectCustomerInfoByIdAn(Long customerId){
        CustomerInfo customerInfo=new CustomerInfo();
        AiDeepseekAnswerTotal aiDeepseekAnswerTotal=new AiDeepseekAnswerTotal();
        aiDeepseekAnswerTotal.setCustomerId(customerId);
        List<AiDeepseekAnswerTotal> aiDeepseekAnswerTotalList=   aiDeepseekAnswerTotalMapper.selectAiDeepseekAnswerTotalList(aiDeepseekAnswerTotal);
        customerInfo.setAiDeepseekAnswerTotalList(aiDeepseekAnswerTotalList);
            AiRecordingDuan aiRecordingDuan=new AiRecordingDuan();
            aiRecordingDuan.setCustomerId(customerId);
         List<AiRecordingDuan> aiRecordingDuanList=   aiRecordingDuanMapper.selectAiRecordingDuanList(aiRecordingDuan);
        aiRecordingDuanList.forEach(duan->{
            AiRecordingDuan aiRecordingDuanSelect=  aiRecordingDuanMapper.selectAiRecordingDuanById(duan.getId());
            List<AiRecordingChild>  aiRecordingChildList=  aiRecordingChildMapper.selectChildBySpokes(aiRecordingDuanSelect);

//            aiRecordingChildList.forEach(child->{
//                if (child.getFilePath().contains(".wav")){
//                    child.setFilePath(child.getFilePath().split(".wav")[0]);
//                }
//            });


            duan.setAiRecordingChildList(aiRecordingChildList);
        });
        customerInfo.setAiRecordingDuanList(aiRecordingDuanList);
        return  customerInfo;
    }


    @Override
    public List<CustomerInfo> selectCustomerInfoListPage(CustomerInfo customerInfo)
    {
        Long userId= SecurityUtils.getUserId();
        SysUserRole sysUserRole =new SysUserRole();
        sysUserRole.setRoleId(100L);
        sysUserRole.setUserId(userId);
        Integer coun= sysUserRoleMapper.countUserRoleByRoleIdUserId(sysUserRole);
        if (coun == 0 && userId!=1L){
            customerInfo.setUserId(userId);
        }
        customerInfo.setEffective("1");
        PageUtils.startPage();
        List<CustomerInfo> customerInfoList=  customerInfoMapper.selectCustomerInfoList(customerInfo);
        return customerInfoList;
    }


    @Override
    public List<CustomerCountTwoVo> selectCustomerInfoListProduct(CustomerInfo customerInfo)
    {
        List<CustomerCountVo> customerCountVoListResult=new ArrayList<>();
        List<CustomerCountVo>  customerCountVoList= customerInfoMapper.selectCustomerProduct();
        customerCountVoList.forEach(customer -> {
            List<String> list = Arrays.asList(customer.getContent().split(","));
            list.forEach(con->{
                CustomerCountVo customerCountVo=new CustomerCountVo();
                customerCountVo.setContent(con);
                customerCountVo.setCount(customer.getCount());
                customerCountVoListResult.add(customerCountVo);
            });
        });
        // 按 product 分组，并对 quantity 求和
        Map<String, Integer> groupedSum = customerCountVoListResult.stream()
                .collect(Collectors.groupingBy(
                        CustomerCountVo::getContent, // 按 product 分组
                        Collectors.summingInt(CustomerCountVo::getCount) // 对 quantity 求和
                ));
        // 将分组求和的结果转换为 List<Order>
        List<CustomerCountTwoVo> result = groupedSum.entrySet().stream()
                .map(entry -> new CustomerCountTwoVo(entry.getKey(), entry.getValue())) // 创建新的 Order 对象
                .collect(Collectors.toList());

        Collections.sort(result, new Comparator<CustomerCountTwoVo>() {
            @Override
            public int compare(CustomerCountTwoVo e1, CustomerCountTwoVo e2) {
                // 假设 fieldName 是 Comparable 类型（如 String, Integer, Date 等）
                return e2.getCount().compareTo(e1.getCount());
            }
        });

        return result;
    }

    @Override
    public List<CustomerCountTwoVo> selectCustomerInfoListHindrances(CustomerInfo customerInfo)
    {
        List<CustomerCountVo> customerCountVoListResult=new ArrayList<>();
        List<CustomerCountVo>  customerCountVoList= customerInfoMapper.selectCustomerHindrances();
        customerCountVoList.forEach(customer -> {
            List<String> list = Arrays.asList(customer.getContent().split(","));
            list.forEach(con->{
                CustomerCountVo customerCountVo=new CustomerCountVo();
                customerCountVo.setContent(con);
                customerCountVo.setCount(customer.getCount());
                customerCountVoListResult.add(customerCountVo);
            });
        });
        // 按 product 分组，并对 quantity 求和
        Map<String, Integer> groupedSum = customerCountVoListResult.stream()
                .collect(Collectors.groupingBy(
                        CustomerCountVo::getContent, // 按 product 分组
                        Collectors.summingInt(CustomerCountVo::getCount) // 对 quantity 求和
                ));
        // 将分组求和的结果转换为 List<Order>
        List<CustomerCountTwoVo> result = groupedSum.entrySet().stream()
                .map(entry -> new CustomerCountTwoVo(entry.getKey(), entry.getValue())) // 创建新的 Order 对象
                .collect(Collectors.toList());
        Collections.sort(result, new Comparator<CustomerCountTwoVo>() {
            @Override
            public int compare(CustomerCountTwoVo e1, CustomerCountTwoVo e2) {
                // 假设 fieldName 是 Comparable 类型（如 String, Integer, Date 等）
                return e2.getCount().compareTo(e1.getCount());
            }
        });
        return result;
    }


    @Override
    public List<CustomerCountVo> selectCustomerInfoListIndustry(CustomerInfo customerInfo)
    {
        List<CustomerCountVo>  customerCountVoList= customerInfoMapper.selectCustomerIndustry();
        return customerCountVoList;


    }
    @Override
    public List<CustomerCountVo> selectCustomerInfoListZong(CustomerInfo customerInfo)
    {
        List<CustomerCountVo>  customerCountVoList= customerInfoMapper.selectCustomerZong();
        return customerCountVoList;

//        List<Long> userIdsList=new ArrayList<>();
//        Long userId= SecurityUtils.getUserId();
//        SysUserRole sysUserRole =new SysUserRole();
//        sysUserRole.setRoleId(100L);
//        sysUserRole.setUserId(userId);
//        Integer coun= sysUserRoleMapper.countUserRoleByRoleIdUserId(sysUserRole);
//        if (coun == 0 && userId!=1L){
//            userIdsList.add(userId);
//        }else{
//          String   userIdsss= customerInfoMapper.selectSaleUserId();
//            // 去重并转换为 List<Long>
//            userIdsList = Arrays.stream(userIdsss.split(",")) // 按逗号分隔
//                    .map(String::trim) // 去除空格
//                    .filter(s -> !s.isEmpty()) // 过滤空字符串
//                    .distinct() // 去重
//                    .map(s -> {
//                        try {
//                            return Long.parseLong(s); // 尝试转换为 Long
//                        } catch (NumberFormatException e) {
//                            System.err.println("无法将字符串转换为 Long: " + s);
//                            return null; // 转换失败返回 null
//                        }
//                    })
//                    .filter(Objects::nonNull) // 过滤掉 null 值
//                    .collect(Collectors.toList()); // 收集为 List<Long>
//        }
//        userIdsList.forEach(userIdLong->{
//            CustomerZongVo customerZongVo=new CustomerZongVo();
//          SysUser sysUser=  sysUserMapper.selectUserById(userIdLong);
//            List<Long> customerIds=  customerInfoMapper.selectCustomerToCount(userIdLong);
//            customerZongVo.setUserNames(sysUser.getUserName());
//            customerZongVo.setCustomerCount(customerIds.size());
//
//
//        });
//      return null;
    }



    /**
     * 新增客户数据
     *
     * @param customerInfo 客户数据
     * @return 结果
     */
    @Override
    public int insertCustomerInfo(CustomerInfo customerInfo)
    {
        customerInfo.setCreateBy(SecurityUtils.getUsername());
        customerInfo.setCreateById(SecurityUtils.getUserId());
        customerInfo.setCreateTime(DateUtils.getNowDate());
        customerInfo.setSaleStr(SecurityUtils.getUserId()+"");
        return customerInfoMapper.insertCustomerInfo(customerInfo);
    }

    /**
     * 修改客户数据
     *
     * @param customerInfo 客户数据
     * @return 结果
     */
    @Override
    public int updateCustomerInfo(CustomerInfo customerInfo)
    {
        customerInfo.setUpdateTime(DateUtils.getNowDate());
        return customerInfoMapper.updateCustomerInfo(customerInfo);
    }

    /**
     * 批量删除客户数据
     *
     * @param ids 需要删除的客户数据主键
     * @return 结果
     */
    @Override
    public int deleteCustomerInfoByIds(Long[] ids)
    {
        CustomerInfo customerInfo = new CustomerInfo();
        customerInfo.setId(ids[0]);
        customerInfo.setDelFlag("1");
        return  customerInfoMapper.updateCustomerInfo(customerInfo);
//         customerInfoMapper.deleteCustomerInfoByIds(ids);
    }

    /**
     * 删除客户数据信息
     *
     * @param id 客户数据主键
     * @return 结果
     */
    @Override
    public int deleteCustomerInfoById(Long id)
    {
        return customerInfoMapper.deleteCustomerInfoById(id);
    }
}
